package com.weds.frame.common.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2023/3/17 09:23
 */
public class AES {
    final static String AES_KEY = "k;)*(+nmjdsf$#@d";
    /**
     * AES加密
     *
     * @param str
     *            待加密字符串
     * @return 加密后字符串
     */
    public static String aesEncrypt(String str) {
        return aesEncrypt(AES_KEY,str);
    }
    /**
     * AES解密
     *
     * @param str
     *            待解密字符串
     * @return 解密后字符串
     */
    public static String aesDecrypt(String str) {
        return aesDecrypt(AES_KEY,str);
    }
    /**
     * AES加密
     *
     * @param str
     *            待加密字符串
     * @return 加密后字符串
     */
    public static String aesEncrypt(String aes_KEY,String str) {
        try {
            str=new String(str.getBytes("UTF-8"),"UTF-8");
            String password = aes_KEY;
            SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] bs=cipher.doFinal(str.getBytes("UTF-8"));
            byte[] bs64= Base64.getEncoder().encode(bs);
            String strTmp = new String(bs64);
            return strTmp;

        } catch (Exception e) {
            throw new RuntimeException("AES加密时异常"+e.getMessage());
        }
    }

    /**
     * AES解密
     *
     * @param str
     *            待解密字符串
     * @return 解密后字符串
     */
    public static String aesDecrypt(String aes_KEY,String str) {
        try {
            if (str==null||str.isEmpty()) {
                return "";
            }
            String password = aes_KEY;
            SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte [] bs= Base64.getDecoder().decode(str.replace(" ","+"));
            String strTmp = new String(cipher.doFinal(bs),"UTF-8");
            return strTmp;

        } catch (Exception ex) {
            throw new RuntimeException("AES解时异常"+ex.getMessage());
        }
    }
}
